package com.zrq.secondkill.controller;

import com.zrq.secondkill.controller.viewobject.ItemVO;
import com.zrq.secondkill.response.CommonReturnType;
import com.zrq.secondkill.service.ItemService;
import com.zrq.secondkill.service.model.ItemModel;
import com.zrq.secondkill.service.model.PromoModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/item")
@CrossOrigin(origins = {"*"}, allowCredentials = "true")
public class ItemController {

    final
    ItemService itemService;

    public ItemController(ItemService itemService) {
        this.itemService = itemService;
    }

    @GetMapping("/list")
    public CommonReturnType listItem() {
        return CommonReturnType.create(itemService.listItem());
    }

    @GetMapping("/get")
    public CommonReturnType getItem(@RequestParam(name = "id") String id) {
        ItemModel itemModel = itemService.getItemByIdInCache(Integer.parseInt(id));
        ItemVO itemVO = convertItemVOFromItemModel(itemModel);
        return CommonReturnType.create(itemVO);
    }

    private static ItemVO convertItemVOFromItemModel(ItemModel itemModel) {
        ItemVO itemVO = new ItemVO();
        BeanUtils.copyProperties(itemModel, itemVO);
        PromoModel promoModel = itemModel.getPromoModel();
        if (promoModel != null) {
            itemVO.setPromoStatus(promoModel.getStatus().getStatus());
            itemVO.setPromoPrice(promoModel.getPromoItemPrice());
            itemVO.setPromoId(promoModel.getId());
            if (promoModel.getStartDate() != null) {
                itemVO.setStartDate(promoModel.getStartDate().toString());
            }
            if (promoModel.getEndDate() != null) {
                itemVO.setEndDate(promoModel.getEndDate().toString());
            }
        }
        return itemVO;
    }
}
